/**
 * Copyright (c) 2020, Mr.Wang (recallcode@aliyun.com) All rights reserved.
 */

package com.cpipec.demo.train.imp;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.PageResult;
import cn.hutool.db.Session;
import com.alibaba.fastjson.JSONObject;
import com.cpipec.demo.spi.BPMServerRestClient;
import com.cpipec.demo.train.TrainService;
import com.cpipec.demo.vo.PageResultVO;
import com.cpipec.demo.vo.TrainVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class TrainServiceImpl implements TrainService {

	private static Logger logger = LoggerFactory.getLogger(TrainServiceImpl.class);

	@Autowired
	private DataSource dataSource;

	@Autowired
	private BPMServerRestClient bpmServerRestClient;

	@Override
	public PageResultVO<Entity> getTrainList(String username, int page, int pageSzie) {
		try {
			Session session = Session.create(dataSource);
			Entity entity = Entity.create("train_project");
			entity.set("createName", username);
			PageResult<Entity> pageResult = session.page(entity, page, pageSzie);
			List<Entity> entityList = new ArrayList<Entity>();
			Arrays.stream(pageResult.toArray()).forEach(object -> {
				Entity en = (Entity) object;
				String bpmResult = bpmServerRestClient.getIncidentInfo(en.getStr("instanceId"));
				String status = JSONObject.parseObject(bpmResult).getJSONObject("ObjRetVal").getString("dwStatus");
				en.set("status", status);
				entityList.add(en);
			});
			return new PageResultVO<Entity>(entityList, pageResult.getTotal());
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	@Override
	public boolean save(TrainVO trainVO) {
		Session session = Session.create(dataSource);
		try {
			String id = IdUtil.simpleUUID();
			trainVO.setId(id);
			Entity entity = Entity.create("train_project");
			entity.set("id", id);
			entity.set("projectName", trainVO.getProjectName());
			entity.set("zbDep", trainVO.getZbDep());
			entity.set("jbEmp", trainVO.getJbEmp());
			entity.set("trainDate", trainVO.getTrainDate());
			entity.set("trainContent", trainVO.getTrainContent());
			entity.set("trainPurpose", trainVO.getTrainPurpose());
			entity.set("trainCost", trainVO.getTrainCost());
			entity.set("createName", trainVO.getCreateName());
			session.beginTransaction();
			String bpmResult = bpmServerRestClient.launchSendTask(trainVO);
			String instanceId = JSONObject.parseObject(bpmResult).getString("ObjRetVal");
			if (StrUtil.isNotBlank(instanceId)) {
				entity.set("instanceId", instanceId);
				session.insert(entity);
				session.commit();
				return true;
			} else {
				throw new RuntimeException("启动流程失败");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			session.quietRollback();
			return false;
		}
	}

	@Override
	public Entity getTrain(String id) {
		try {
			Session session = Session.create(dataSource);
			Entity entity = Entity.create("train_project");
			entity.set("id", id);
			return session.get(entity);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	@Override
	public String getViewPic(String instanceId) {
		String bpmResult = bpmServerRestClient.getGetGraphicalStatus(instanceId);
		String picStr = JSONObject.parseObject(bpmResult).getString("ObjRetVal");
		return picStr;
	}
}
